package com.jackchen.common.filter;

import java.io.IOException;
import java.util.HashMap;
import java.util.Date;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.apache.log4j.Logger;

import com.jackchen.common.i18n.UserLocaleCache;
import com.jackchen.po.User;
import com.jackchen.service.UserService;
import com.jackchen.util.DateUtils;


/*
 * Author:
 * Description: this filter is designed to verify the password of logging in,
 * also to screen the resource illegal requested under the condition of un-logging in.
 */
public class LoginFilter implements Filter{
	
	private static final Logger log = Logger.getLogger(LoginFilter.class);
	
	public FilterConfig filterConfig;
	public String LOGIN_USERNAME;//登录用户名
	public String LOGIN_PASSWORD;//登录密码
	public String VERIFY_CODE;//登录校验码
	public String LOGIN_ACTION_URL;//登录表单action响应的URL地址
	
	public static final String LOGIN_PAGE_NAME = "/page/login/login.jsp";
	public static final String HOME_PAGE_NAME = "/page/index/index.jsp";
	public static final String ONLINE_USERLIST = "onlineUserList";
	public static final String SESSION_USER_NAME = "session_userName";
	public static final String SESSION_USER_LANGUAGE = "userLanguage";
	
	//@Autowired
	private UserService userService;
	
	public void init(FilterConfig filterConfig) throws ServletException {
		log.debug("Login filter is initializing");
		this.filterConfig = filterConfig;
		ServletContext servletContext = filterConfig.getServletContext();
		this.LOGIN_USERNAME = servletContext.getInitParameter("LOGIN_USERNAME");
		this.LOGIN_PASSWORD = servletContext.getInitParameter("LOGIN_PASSWORD");
		this.VERIFY_CODE = servletContext.getInitParameter("VERIFY_CODE");
		this.LOGIN_ACTION_URL = servletContext.getInitParameter("LOGIN_ACTION_URL");
		HashMap hashmap = new HashMap();
		servletContext.setAttribute(ONLINE_USERLIST, hashmap);
	}
	
	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain chain) throws IOException, ServletException {
		log.debug("LoginFilter is processing filter task work");
		if(null == this.filterConfig){
			return;
		}
		HttpServletRequest loginRequest = (HttpServletRequest)request;
		HttpServletResponse loginResponse = (HttpServletResponse)response;
		String targetURL = loginRequest.getRequestURI();
		String reuqestURLSuffix = targetURL.substring(targetURL.lastIndexOf(".")+1,targetURL.length());
		
		if(targetURL.indexOf(LOGIN_PAGE_NAME)!=-1){
			chain.doFilter(request, response);
			return;
		}
		
		//登录用户名和密码校验
		if(targetURL.indexOf(LOGIN_ACTION_URL)!=-1){
			String userName = (String)loginRequest.getParameter(LOGIN_USERNAME).trim();
			String password = (String)loginRequest.getParameter(LOGIN_PASSWORD);
			User validateResult = userService.queryUserByUserName(userName,password);
			if(null != validateResult){//成功登陆，则转入主页
				addOnlineUser(loginRequest,userName,password,validateResult.getLanguageflag());
				loginResponse.sendRedirect(loginRequest.getContextPath()+HOME_PAGE_NAME);
				return;
			}else{//错误的用户名或密码
				loginResponse.sendRedirect(loginRequest.getContextPath()+LOGIN_PAGE_NAME+"?errorCode=1");
				return;
			}
		}
//to comment it for this project		
//		boolean logedFlag = isLogedIn(loginRequest);
//		if(false == logedFlag){//未登录状态请求登录状态的页面资源，则自动跳转到登录页面
//			loginResponse.sendRedirect(loginRequest.getContextPath()+LOGIN_PAGE_NAME+"?errorCode=2");
//			return;
//		}
		
		try{
			setNoCache(loginResponse);
			chain.doFilter(request, response);
			return;
		}catch(Exception e){
			log.error("login validate encountered a problem!",e);
		}
		
	}
	/*
	private User userInfoValidate(String a_userName,String a_password){
		User user = userService.queryUserByUserName(a_userName);
		return user;
		
		if(user!=null&&user.getPassword().equals(a_password)){
			return user;
		}else
			return false;
		
	}*/
	
	private void addOnlineUser(HttpServletRequest a_request,String a_username,
							   String a_password,Integer languageFlag)
					throws IOException,ServletException{
		HttpSession  loginSession = a_request.getSession();
		loginSession.setAttribute(SESSION_USER_NAME, a_username);
		loginSession.setAttribute("password", a_password);
		loginSession.setAttribute("onLine", "true");//更改是否登录状态:true，登录;false:未登录.
		String logedInTime = DateUtils.format(new Date());
		loginSession.setAttribute("logedInTime", logedInTime);
		loginSession.setAttribute("sessionId", loginSession.getId());
		loginSession.setAttribute(SESSION_USER_LANGUAGE, languageFlag);
		
		ServletContext servletContext = filterConfig.getServletContext();
		HashMap loginList = (HashMap)servletContext.getAttribute(ONLINE_USERLIST);
		loginList.put(a_username, loginSession);
		
		// 用户登陆成功以后，为本次请求线程设置语言标识
		UserLocaleCache.getInstance().setLangFlag(languageFlag == 0 ? "cn":"en");
	}
	
	private void setNoCache(HttpServletResponse response){
		response.setHeader("Pragma", "No-cache");
		response.setHeader("Cache-Control", "no-cache");
		response.setDateHeader("Expires", 0);
	}
	
	private boolean isLogedIn(HttpServletRequest a_request){
		HttpSession  session = a_request.getSession();
		String isLogedInFlag = (String)session.getAttribute("onLine");
		if("true".equals(isLogedInFlag)){
			return true;
		}else{
			return false;
		}
	}
	
	public void destroy() {
		this.filterConfig = null;
	}

	public UserService getUserService() {
		return userService;
	}

	public void setUserService(UserService userService) {
		this.userService = userService;
	}
	
}
